<?php

namespace app\admin\controller\user;

use app\admin\model\Sysmessage;
use app\admin\model\yalimedia\Course;
use app\common\controller\Backend;
use app\admin\model\UserHistory;
use app\admin\model\User;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class YalimediaCourseUser extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('yalimedia_course_user');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            try {
            $list = $this->model
                ->with('course')
                ->where($where)
                ->where('user_id',input('pid'))
                ->order($sort, $order)
                ->paginate($limit);
            }catch (\Exception $e){
                halt($e);
            }

//            foreach ($list as $k => $v) {
//                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
//                $v->hidden(['password', 'salt']);
//            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $u = User::where('id',input('ids'))->find();
        $this->view->assign('user',$u);
        $this->view->assign('ids',input('ids'));
        return $this->view->fetch();
    }

    public function set_user_course()
    {

        $ids = input()['ids'];
        $pid = input()['pid'];
        $has = $this->model->whereIn('course_id',$ids)->where('user_id',$pid)->select();
        if($has){
            $this->model->whereIn('course_id',$ids)->where('user_id',$pid)->delete();
        }

        $this->model->transaction(function()use($ids,$pid){
            $insertdata = [];
            $message = [];
            $course = [];
            foreach ($ids as $v){
                $insertdata[] = ['user_id'=>$pid, 'course_id'=>$v, 'createtime'=>time(), 'updatetime'=>time()];
                $title = Course::where('id',$v)->value('title');
                $message [] = [
                    'updatetime'=>time(),
                    'createtime'=>time(),
                    'user_id'=>$pid,
                    'title'=>'课程购买通知',
                    'sub_title'=>'您购买的《'.$title.'》课程已下发。',
                    'content'=>'您购买的《'.$title.'》课程已于'.date('Y-m-d H:i:s').'下发。请前往课程页查看'
                ];
                $course[] = [
                    'type'=>0,
                    'user_id'=>$pid,
                    'course_id'=>$v,
                    'createtime'=>time(),
                    'remark'=>'课程购买',
                    'updatetime'=>time()
                ];
                UserHistory::where('user_id',$pid)->where('course_id',$v)->delete();
            }
            Sysmessage::insertAll($message);
            $this->model->insertAll($insertdata);
            UserHistory::insertAll($course);
        });

        $this->success("添加成功");
    }

    public function single()
    {
        if($this->request->isPost()){

            $row = input()['row'];
            $pid = input('pid');
            $this->model->insert([
                'user_id'=>$pid,
                'course_id'=>$row['course_id'],
                'createtime'=>time(),
                'updatetime'=>time()
            ]);
            UserHistory::insert([
                'user_id'=>$pid,
                'course_id'=>$row['course_id'],
                'taobaoorder'=>$row['taobaoorder'],
                'createtime'=>time(),
                'remark'=>$row['remark'],
                'updatetime'=>time()
            ]);
            $title = Course::where('id',$row['course_id'])->value('title');
            Sysmessage::insert([
                'updatetime'=>time(),
                'createtime'=>time(),
                'user_id'=>$pid,
                'title'=>'课程购买通知',
                'sub_title'=>'您购买的《'.$title.'》课程已下发。',
                'content'=>'您购买的《'.$title.'》课程已于'.date('Y-m-d H:i:s').'下发。请前往课程页查看'
            ]);
            $this->success('成功',null,[]);
        }
        $group = collection(Course::field('id,title name')->whereNotIn('id',collection(\app\admin\model\YalimediaCourseUser::where('user_id',input('pid',0))->select())->column('course_id'))->select())->toArray();
        $this->view->assign('departmentList', $group);
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        $pid = input('pid');
        $data = collection($this->model->whereIn('id',$ids)->select())->toArray();
        $this->model->transaction(function ()use($ids,$pid,$data){
            foreach ($data as $v){
                UserHistory::where('user_id',$pid)->where('course_id',$v['course_id'])->delete();
            }
            $this->model->whereIn('id',$ids)->delete();
        });

        $this->success('成功',null,[]);
    }

    public function edit($ids = NULL)
    {
        $pid = input('pid');
        if($this->request->isPost()){
            $ids = input('ids');
            $row = input()['row'];
            $this->model->transaction(function ()use($pid, $ids, $row){
                $origin = $this->model->where('id',$ids)->find();
                $this->model->where('id',$ids)->update([
                    'updatetime'=>time(),
                    'course_id'=>$row['course_id']
                ]);
                $historyid = UserHistory::where('user_id',$pid)->where('course_id',$origin['course_id'])->value('id');

                UserHistory::where('id',$historyid)->update($row);
                if($origin['course_id'] != $row['course_id']){
                    $title = Course::where('id',$row['course_id'])->value('title');
                    Sysmessage::insert([
                        'updatetime'=>time(),
                        'createtime'=>time(),
                        'user_id'=>$pid,
                        'title'=>'课程购买通知',
                        'sub_title'=>'您购买的《'.$title.'》课程已下发。',
                        'content'=>'您购买的《'.$title.'》课程已于'.date('Y-m-d H:i:s').'下发。请前往课程页查看'
                    ]);
                }
            });

            $this->success('成功',null,[]);
        }

        $course_id = $this->model->where('id',$ids)->value('course_id');
        $group = collection(Course::field('id,title name')->select())->toArray();
        $row = collection(UserHistory::where('user_id',$pid)->where('course_id',$course_id)->select())->toArray();

        $row = $row ? $row[0] : [];
        $this->assign('row',$row);
        $this->view->assign('departmentList', $group);
        return $this->view->fetch();
    }
}
